import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_2b_client/apis/CheckInventoryRecordApi.dart';
import 'package:flutter_2b_client/apis/GoodsApi.dart';
import 'package:flutter_2b_client/apis/MarketCheckInventoryRecordApi.dart';
import 'package:flutter_2b_client/apis/MarketDeliveryOrderApi.dart';
import 'package:flutter_2b_client/apis/MarketOrderApi.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:vibration/vibration.dart';

class ScanBarcodePage extends HookWidget {
  static get path => "/scanBarcode";
  final int? marketOrderId;
  final int? marketDeliveryOrderId;
  final int? checkInventoryRecordId;
  final int? marketCheckInventoryRecordId;

  const ScanBarcodePage({
    Key? key,
    this.marketOrderId,
    this.marketDeliveryOrderId,
    this.checkInventoryRecordId,
    this.marketCheckInventoryRecordId,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final validateLoading = useState(false);
    var errorTextState = useState<String?>(null);
    useEffect(() {
      Timer? timer;
      if (errorTextState.value != null) {
        timer = Timer(const Duration(seconds: 3), () {
          errorTextState.value = null;
        });
      }
      return () {
        timer?.cancel();
      };
    }, [errorTextState.value]);
    existsInScope(String barcode) async {
      bool exists = false;
      if (marketOrderId != null) {
        exists = await marketOrderApi.exists(marketOrderId!, barcode);
      } else if (marketDeliveryOrderId != null) {
        exists = await marketDeliveryOrderApi.exists(marketOrderId!, barcode);
      } else if (checkInventoryRecordId != null) {
        exists = await checkInventoryRecordApi.exists(
            checkInventoryRecordId!, barcode);
      } else if (marketCheckInventoryRecordId != null) {
        exists = await marketCheckInventoryRecordApi.exists(
            marketCheckInventoryRecordId!, barcode);
      }
      if (exists) {
        errorTextState.value = "条码已存在";
      }
      return exists;
    }

    existsGoods(String barcode) async {
      var exists = await goodsApi.exists(barcode);
      if (!exists) {
        errorTextState.value = "条码$barcode不存在";
      }
      return exists;
    }

    validate(String barcode) async {
      validateLoading.value = true;
      try {
        return !await existsInScope(barcode) && await existsGoods(barcode);
      } catch (e) {
        errorTextState.value = "条码校验失败:${e.toString()}";
        return false;
      } finally {
        validateLoading.value = false;
      }
    }

    var detectingState = useState(false);

    var themeData = Theme.of(context);
    return Stack(
      alignment: Alignment.center,
      children: [
        Positioned.fill(
          child: MobileScanner(
            overlay: Scaffold(
              backgroundColor: Colors.transparent,
              appBar: AppBar(
                elevation: 0,
                backgroundColor: Colors.transparent,
                leading: IconButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  icon: const Icon(Icons.arrow_back),
                  color: Theme.of(context).colorScheme.surfaceVariant,
                  style: ButtonStyle(
                    backgroundColor: MaterialStatePropertyAll(
                      Theme.of(context)
                          .colorScheme
                          .inverseSurface
                          .withOpacity(0.4),
                    ),
                  ),
                ),
              ),
            ),
            controller:
                MobileScannerController(detectionSpeed: DetectionSpeed.normal),
            onDetect: (barcodes) async {
              if (detectingState.value == true) return;
              detectingState.value = true;
              try {
                var firstBarcode = barcodes.barcodes.where((element) => element.format != BarcodeFormat.qrCode).firstOrNull;
                if (!validateLoading.value &&
                    firstBarcode != null &&
                    firstBarcode.rawValue != null &&
                    (await validate(firstBarcode.rawValue!)) &&
                    context.mounted) {
                  context.pop(firstBarcode.rawValue);
                  if (await Vibration.hasVibrator() == true) {
                    Vibration.vibrate();
                  }
                } else {
                  detectingState.value = false;
                }
              } catch (e) {
                detectingState.value = false;
              }
            },
          ),
        ),
        if (errorTextState.value != null)
          Positioned(
            bottom: 200,
            child: Text(
              errorTextState.value!,
              style:
                  themeData.textTheme.bodyLarge?.copyWith(color: Colors.white),
            ),
          ),
      ],
    );
  }
}
